package com.michale.framework.security.context;

import com.alibaba.fastjson2.JSON;
import com.michale.common.codemessage.HTTPCodeMessage;
import com.michale.common.constants.CommonConstant;
import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.result.AjaxResult;
import com.michale.common.utils.Ip.ServletUtils;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.framework.config.async.asyncFactory.AsyncTask;
import com.michale.framework.config.async.manager.AsyncManager;
import com.michale.framework.security.service.TokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Michale
 * @apiNote 自定义退出处理类 返回成功
 */
@Component
public class LogOutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private TokenService tokenUtils;
    @Resource
    private RedisUtils redisUtils;
    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUserDetail loginUserDetail = tokenUtils.getLoginUser(request);
        if (StringUtils.isNotNull(loginUserDetail)) {
            String userName = loginUserDetail.getUsername();
            // 删除用户缓存记录
            tokenUtils.deleteLoginUser(loginUserDetail.getToken());
            redisUtils.deleteObject(RedisCacheConstant.LOGIN_KEY + loginUserDetail.getUsername());
            //记录用户退出日志
            AsyncManager.asyncManager().start(AsyncTask.recordLoginInfo(userName, CommonConstant.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HTTPCodeMessage.SUCCESS.getCode(), "退出成功")));
    }
}
